<?php

/**
 * 后台Controller
 */
//定义是后台
namespace Robot\Controller;
use OSS\OssClient;
use OSS\Core\OssException;

class AdminbaseController extends AppframeController {

    //OSS
    protected $ossClient;

    protected $parameter;

    protected $currentModel;

    function _initialize(){
        parent::_initialize();

        $host = $_SERVER['HTTP_HOST'];
        $moduleName = strtolower(MODULE_NAME);

        if($host == C("FRONTEND_HOST")
            && $moduleName != "wechat") {
            header("Location:http://".$host."/wechat");
            exit();
        } else if($host == C("BACKEND_HOST")
            && $moduleName != "admin") {
            header("Location:http://".$host."/admin");
            exit();
        } else if($host == C("ROBOT_HOST")
            && $moduleName != "robot") {
            header("Location:http://".$host."/robot");
            exit();
        }

        $this->assign("admin","机器人管理员");
    	if(isset($_SESSION['ROBOT_ID'])
            && $_SESSION['ROBOT_ID'] == "Qkt1qazxsw2-123456"){
    		$this->assign("admin","机器人管理员");
    	}else{
    		//$this->error("您还没有登录！",U("admin/public/login"));
    		if(IS_AJAX){
    			$this->error("您还没有登录！",U("robot/public/login"));
    		}else{
    			header("Location:".U("robot/public/login"));
    			exit();
    		}

    	}

        //OSS初始化
        vendor("OSS.autoload");

        $accessKeyId = C("OSS_ACCESS_KEY_ID");
        $accessKeySecret = C("OSS_ACCESS_KEY_SECRET");
        $endpoint = C("OSS_ENDPOINT");

        try {
            $this->ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false /* use cname */);
        } catch (OssException $e) {
            print $e->getMessage();
        }

        $this->ossClient->setTimeout(3600);
        $this->ossClient->setConnectTimeout(10);


    }

    function convertRequestToMap() {
        $map = null;

        foreach($_REQUEST as $key => $value) {
            if($key != "p" && $key != "menuid"
                && !isNullOrEmpty($value)) {
                $map[$key] = $value;
                $this->parameter[$key] = $value;
                $arr1 = explode('-',$key);
                $arr2 = explode('#', $arr1[0]);
                $trueKey = count($arr2) > 1 ? $arr2[1] : $arr2[0];
                $this->assign($trueKey, $value);
            }
        }

        return $map;
    }

    /**
     * 进入添加页
     */
    public function add() {
        $this->display();
    }

    /**
     * 进入编辑页
     */
    public function edit() {

        $id = $_REQUEST['id'];
        $info = $this->currentModel->queryById($id);

        $this->assign('info', $info);
        $this->display();

    }

    /**
     * 根据id删除
     */
    public function delete() {

        $id = $_REQUEST['id'];

        $this->currentModel->deleteById($id);

        $this->success('删除成功!');

    }

    //OSS上传文件
    function uploadFileToOss($filePath, $object) {
        $bucket = C('OSS_BUCKET_NAME');
        try{
            $this->ossClient->uploadFile($bucket, $object, $filePath);

        } catch(OssException $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return;
        }
    }

    //OSS获取图片链接
    function getFileUrlFromOss($object, $isCompress = false) {

        if(!$isCompress) {
            $url = 'http://' .C('OSS_ENDPOINT_CNAME'). '/' .$object;
        } else {
            $url = 'http://' .C('OSS_IMAGE_ENDPOINT'). '/' .$object;
        }

        return $url;

    }

    //OSS分片上传
    function multiUploadFileToOss($filePath, $object, $options='') {
        $bucket = C('OSS_BUCKET_NAME');
        try{
            $this->ossClient->multiuploadFile($bucket, $object, $filePath, $options);
        } catch(OssException $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return;
        }
        //print(__FUNCTION__ . ":  OK" . "\n");

    }

    //图片缩放
    function compressImageByOss($object,$width,$height) {
        $url = 'http://' .C('OSS_IMAGE_ENDPOINT'). '/' .$object. '@' .$width. 'w_' .$height. 'h';
        return $url;
    }

    //图片水印
    function watermarkImageByOss($object,$text) {

        $watermark = '2';
        $text = str_replace('=','',url_safe_base64_encode($text));
        $type = str_replace('=','',url_safe_base64_encode('wqy-zenhei'));
        $color = str_replace('=','',url_safe_base64_encode('#FFFFFF'));
        $size = '40';
        $t = '50';
        $p = '9';

        $url = 'http://' .C('OSS_IMAGE_ENDPOINT'). '/' .$object. '@' .'watermark=' .$watermark. '&text=' .$text. '&type=' .$type. '&size=' .$size. '&color=' .$color. '&t=' .$t. '&p=' .$p;

        return $url;

    }

    function ueditorUpload() {
        $data = new \Org\Util\Ueditor();
        echo $data->output();
    }

    function downloadFile() {

        $filePath = I('get.filePath');

        $fileName = I('get.fileName');

        if (!file_exists($filePath)) {   //检查文件是否存在  
            echo "文件找不到";
            exit;
        } else {
            $file = fopen($filePath, "r"); // 打开文件
            // 输入文件标签
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Accept-Length: " . filesize($filePath));
            Header("Content-Disposition: attachment; filename=" . $fileName);
            // 输出文件内容
            echo fread($file, filesize($filePath));
            fclose($file);
            exit();
        }
    }
    function uploadFile() {

        $targetFolder = '/Uploads/files'; // Relative to the root

        if (!empty($_FILES)) {

            $tempFile = $_FILES['Filedata']['tmp_name'];
            $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;

            $fileParts = pathinfo($_FILES['Filedata']['name']);

            $object = md5(time()) . '.'. $fileParts['extension'];

            $targetFile = rtrim($targetPath,'/') . '/' . $object;

            move_uploaded_file($tempFile,$targetFile);

            $data['url'] = $targetFolder. '/' . $object;
            $data['file'] = $targetFile;
            $data['extension'] = $fileParts['extension'];

            echo json_encode($data);

        }
    }

    function deleteLocalFile() {
        $file = I('post.file');
        unlink($file);
    }

    function uploadImage() {
        $targetFolder = '/Uploads/files'; // Relative to the root

        if (!empty($_FILES)) {

            $tempFile = $_FILES['fileToUpload']['tmp_name'];
            $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;

            $fileParts = pathinfo($_FILES['fileToUpload']['name']);

            $object = md5(uniqid(mt_rand(), true)) . '.' . $fileParts['extension'];

            $targetFile = rtrim($targetPath, '/') . '/' . $object;

            move_uploaded_file($tempFile, $targetFile);

            $this->uploadFileToOss($targetFile,'image/'.$object);

            unlink($targetFile);

            echo json_encode($this->getFileUrlFromOss('image/'.$object));

        }
    }
    
    /**
     * 消息提示
     * @param type $message
     * @param type $jumpUrl
     * @param type $ajax 
     */
    public function success($message = '', $jumpUrl = '', $ajax = false) {
        parent::success($message, $jumpUrl, $ajax);
    }

    /**
     * 模板显示
     * @param type $templateFile 指定要调用的模板文件
     * @param type $charset 输出编码
     * @param type $contentType 输出类型
     * @param string $content 输出内容
     * 此方法作用在于实现后台模板直接存放在各自项目目录下。例如Admin项目的后台模板，直接存放在Admin/Tpl/目录下
     */
    public function display($templateFile = '', $charset = '', $contentType = '', $content = '', $prefix = '') {
        parent::display($this->parseTemplate($templateFile), $charset, $contentType);
    }
    
    
    /**
     * 自动定位模板文件
     * @access protected
     * @param string $template 模板文件规则
     * @return string
     */
    public function parseTemplate($template='') {
    	$tmpl_path=C("SP_ADMIN_TMPL_PATH");
		// 获取当前主题名称
		$theme      =    C('SP_ADMIN_DEFAULT_THEME');
		
		if(is_file($template)) {
			// 获取当前主题的模版路径
			define('THEME_PATH',   $tmpl_path.$theme."/");
			return $template;
		}
		$depr       =   C('TMPL_FILE_DEPR');
		$template   =   str_replace(':', $depr, $template);
		
		// 获取当前模块
		$module   =  MODULE_NAME."/View";
		if(strpos($template,'@')){ // 跨模块调用模版文件
			list($module,$template)  =   explode('@',$template);
		}
		// 获取当前主题的模版路径
		define('THEME_PATH',   $tmpl_path.$theme."/");
		
		// 分析模板文件规则
		if('' == $template) {
			// 如果模板文件名为空 按照默认规则定位
			$template = CONTROLLER_NAME . $depr . ACTION_NAME;
		}elseif(false === strpos($template, '/')){
			$template = CONTROLLER_NAME . $depr . $template;
		}
		
		C("TMPL_PARSE_STRING.__TMPL__",__ROOT__."/".THEME_PATH);
		
		C('SP_VIEW_PATH',$tmpl_path);
		C('DEFAULT_THEME',$theme);
		
		$file=THEME_PATH.$module.'/'.$template.C('TMPL_TEMPLATE_SUFFIX');
		if(!is_file($file)) E(L('_TEMPLATE_NOT_EXIST_').':'.$file);
		return $file;
    }


    /**
     * 初始化后台菜单
     */
    public function initMenu() {
        return D("AdminMenu")->select();
    }

    /**
     *  排序 排序字段为listorders数组 POST 排序字段为：listorder
     */
    protected function _listorders($model) {
        if (!is_object($model)) {
            return false;
        }
        $pk = $model->getPk(); //获取主键名称
        $ids = $_POST['listorders'];
        foreach ($ids as $key => $r) {
            $data['listorder'] = $r;
            $model->where(array($pk => $key))->save($data);
        }
        return true;
    }

    protected function page($Total_Size = 1, $Page_Size = 0, $Current_Page = 1, $listRows = 6, $PageParam = '', $PageLink = '', $Static = FALSE) {
        import('@.Util.Page');
        if ($Page_Size == 0) {
            $Page_Size = C("PAGE_LISTROWS");
        }
        if (empty($PageParam)) {
            $PageParam = C("VAR_PAGE");
        }
        $Page = new \Page($Total_Size, $Page_Size, $Current_Page, $listRows, $PageParam, $PageLink, $Static);
        $Page->SetPager('Admin', '{first}{prev}&nbsp;{liststart}{list}{listend}&nbsp;{next}{last}', array("listlong" => "9", "first" => "首页", "last" => "尾页", "prev" => "上一页", "next" => "下一页", "list" => "*", "disabledclass" => ""));
        return $Page;
    }

    private function check_access($uid){
    	
    	//如果用户角色是1，则无需判断
    	if($uid == 1){
    		return true;
    	}
    	if(MODULE_NAME.CONTROLLER_NAME.ACTION_NAME!="AdminIndexindex"){
    		return sp_auth_check($uid);
    	}else{
    		return true;
    	}
    }


    //获取城市列表
    public function getLevelTwoRegion() {

        $id = I('post.id');

        $regionMap['pid'] = $id;
        $regionMap['grade'] = 2;
        $regionList = D('region')
            ->field("name")
            ->where($regionMap)
            ->order("regionId asc")
            ->select();

        $html = '<option value="0">请选择城市</option>';
        foreach ($regionList as $region) {
            $html .= "<option value = " .$region['name']. ">" . $region['name'] . "</option>";
        }

        echo $html;

    }
}